<template>
    <el-table
        :data="allData"
        border
        ref="table"
        height="100%"
        style="width: 100%;"
        row-key="id"
        @filter-change="filterChange"
        @row-click="handleRowClick">
        <el-table-column
            header-align="center"
            align="center"
            prop="namewc"
            label="类型" >
            <template slot-scope="scope">
                <span class="type-name" :style="{background:scope.row.colour}">{{scope.row.namewc}}</span>
            </template>
        </el-table-column>
        <el-table-column
            v-if="canFilter"
            prop="ld"
            label="楼栋"
            width="90"
            column-key="ld"
            align="center"
            :filters="filter_ld"
            :filter-method="filterMethod">
        </el-table-column>
        <el-table-column
            v-if="canFilter"
            prop="lc"
            label="楼层"
            width="110"
            column-key="lc"
            align="center"
            :filters="filter_lc"
            :filter-method="filterMethod"
            :sortable="true"
            :sort-method="sortByFloor"> <!-- 注意sort-method是属性不是方法 用:不用@ 需要在sortable为true情况下使用 自定义排序 返回排序结果即可 -->
        </el-table-column>
        <el-table-column
            v-if="canFilter"
            prop="ks"
            label="科室"
            width="150"
            column-key="ks"
            align="center"
            :filters="filter_ks"
            :filter-method="filterMethod">
            <template slot-scope="scope">
                <span>{{scope.row.ks}}</span>
                <span class="tooltips" v-if="scope.row['logs'] != null && scope.row['logs'].length > 0">
                    <el-popover
                        placement="top"
                        trigger="hover">
                        <div class="record-item" v-for="(val, idx) in computedWays(scope.row['logs'])" :key="idx">
                            <span>{{val.uname}}</span>
                            <span> 于 {{val.ctime}}</span>
                            <span> 将
                                <span class="red">{{val.old_place}}</span>
                                {{val.way > 0 ? (val.way==1?'修改':'合并') : '设置'}}为
                                <span class="red">{{val.place}}</span>
                            </span>
                        </div>
                        <span slot="reference">
                            <i slot="reference" class="el-icon-question"></i>
                        </span>
                    </el-popover>
                </span>
            </template>
        </el-table-column>
        <el-table-column
            v-if="!canFilter"
            prop="place"
            label="科室"
            width="150"
            align="center">
        </el-table-column>
        <el-table-column
            v-for="(item,index) in judgeTag(tableCol)"
            :key="index"
            align="center"
            :label="item.label"
            :prop="item.prop"
            :width="item.width">
            <template slot-scope="scope">
                <div v-if="item.label == '时间节点'">
                    <div slot="reference" class="popover" v-if="scope.row.uname.indexOf('网络称') != -1">
                        <template>
                            <el-popover trigger="hover" placement="top">
                                <div>
                                    <p v-if="scope.row.sign1_time == ''">收运时间：暂无</p>
                                    <p v-else>收运时间：{{scope.row.sign1_time}} {{scope.row.sign1_uname}}</p>
                                    <p v-if="scope.row.ctime == ''">产生时间：暂无</p>
                                    <p v-else>产生时间：{{scope.row.ctime}} {{scope.row.uname}}</p>
                                </div>
                                <div slot="reference">
                                    <img class="small-icon" src="/static/img/time.png" alt="">
                                </div>
                            </el-popover>
                            <span size="medium">{{scope.row.sign1_time == '' ? '暂无' : scope.row.sign1_time}}</span>
                        </template>
                    </div>
                    <div slot="reference" class="popover" v-else>
                        <!-- 仅妇儿中心的非网络称的时间节点改为多行显示 -->
                        <template v-if="currHospitalId == 1 || currHospitalId == 7 || currHospitalId == 8">
                            <el-popover trigger="hover" placement="top">
                                <div>
                                    <p v-if="scope.row.pctime == ''">产生时间：暂无</p>
                                    <p v-else>产生时间：{{scope.row.pctime}}</p>
                                    <p v-if="scope.row.ctime == ''">收运时间：暂无</p>
                                    <p v-else>收运时间：{{scope.row.ctime}}</p>
                                </div>
                                <div slot="reference">
                                    <img src="/static/img/time.png" alt="">
                                </div>
                            </el-popover>
                        </template>
                        <span size="medium" v-if="currHospitalId == 1 || currHospitalId == 7 || currHospitalId == 8">{{scope.row.pctime == '' ? '暂无' : scope.row.pctime}}</span>
                        <span size="medium" v-else>{{scope.row.ctime}}</span>
                    </div>
                </div>
                <div v-else-if="item.label == '重量'">
                    <template>
                        <div v-if="scope.row['subweight'] != 'kg'"> <!-- 如果subweight不为空，则用subweight，并显示图标 -->
                            <span>{{scope.row['subweight']}}</span>
                            <el-popover trigger="hover" placement="top">
                                <div>
                                    <span>减重前：{{scope.row['weight']}}</span>
                                </div>
                                <span slot="reference">
                                    <i slot="reference" class="el-icon-warning-outline"></i>
                                </span>
                            </el-popover>
                        </div>
                        <div v-else>
                            <span>{{scope.row[item.prop]}}</span>
                        </div>
                    </template>
                </div>
                <div v-else-if="item.label == '条形码'">
                  <span>{{scope.row[item.prop]}}</span>
                  <template v-if="canShowPrintInfo">
                    <template v-if="scope.row.uname.indexOf('网络称') != -1">
                      <el-popover placement="top" trigger="hover">
                        <span v-if="scope.row.ribbon_code !== ''">绑定扎带编号：{{scope.row.ribbon_code}}</span>
                        <span>wifi称编号：{{scope.row.uname.replace('网络称', '')}}</span>
                        <span slot="reference">
                          <i slot="reference" class="el-icon-question"></i>
                        </span>
                      </el-popover>
                    </template>
                    <template v-else-if="scope.row.uname.indexOf('网络称') == -1 && scope.row.print_info_all">
                      <el-popover placement="top" trigger="hover">
                        <div class="record-item">
                          <p v-if="scope.row.ribbon_code !== ''">绑定扎带编号：{{scope.row.ribbon_code}}</p>
                          <span class="red">{{scope.row.print_info_name}} {{scope.row.print_info_phone}}</span>
                          <span> 于 </span>
                          <span class="red">{{scope.row.pctime}}</span>
                          <span> 使用 </span>
                          <span class="red">{{scope.row.platform_name}}</span>
                          <span> 打印 </span>
                        </div>
                        <span slot="reference">
                          <i slot="reference" class="el-icon-question"></i>
                        </span>
                      </el-popover>
                    </template>
                  </template>
                </div>
                <span v-else>{{scope.row[item.prop]}}</span>
            </template>
            <div v-if="item.label == '科室交接'">
                <el-table-column
                    v-for="(val, idx) in item.sub"
                    :key="idx"
                    align="center"
                    :label="val.label"
                    :prop="val.prop"
                    :width="val.width">
                    <template slot-scope="scope">
                        <div v-if="item.label == '科室交接' && val.label == '交接时间'">
                            <span v-if="currHospitalId == 21 || currHospitalId == 22">{{scope.row.step == '0' ? '' : '已确认'}}</span>
                            <span v-else>{{scope.row.step1_time}}</span>
                        </div>
                        <div v-else-if="item.label == '科室交接' && val.label == '交接确认'">
                            <span>{{scope.row.step1_uinfo ? scope.row.step1_uinfo : scope.row.step1_uname}}</span>
                            <!-- <span v-if="scope.row.step1_uinfo != '' && scope.row.step1_uname != ''">，</span>
                            <span>{{scope.row.step1_uname}}</span> -->
                            <div v-if="scope.row.step1_sign != ''">
                                <img :src="scope.row.step1_sign" alt="" @click.stop="handleShowSign(scope, scope.row.step1_sign)" style="width: 25px;vertical-align: middle;">
                            </div>
                        </div>
                        <div v-else-if="val.label == '交接确认'">
                            <span>{{scope.row.step2_uinfo}}</span>
                            <div v-if="scope.row.step2_sign != ''">
                                <img class="pic-item" :src="scope.row.step2_sign" alt="" @click.stop="handleShowSign(scope, scope.row.step2_sign)" style="width: 25px;vertical-align: middle;">
                            </div>
                        </div>
                        <div v-else>
                            <span>{{scope.row[val.prop]}}</span>
                        </div>
                    </template>
                </el-table-column>
            </div>
        </el-table-column>
        <el-table-column fixed="right" label="操作" align="center" v-if="isShowModify && tag == ''">
            <template slot-scope="scope">
                <el-button size="mini" @click.stop="handleShowModal(scope)">修改</el-button>
            </template>
        </el-table-column>
    </el-table>
</template>

<script>
import cookie from '../../common/cookie'
export default {
    props:{
        data:{
            type: Array
        },
        isShowModify:{
            type: Boolean,
            default: false
        },
        restData:{
            type: Array,
            default: () => []   // props default 数组/对象的默认值应当由一个工厂函数返回
        },
        canFilter:{
            type: Boolean,
            default: false
        },
        info:{
            type: Array,
            default: () => []
        },
        tag: {
            type: String,
            default: ''
        },
        canShowPrintInfo: {
          type: Boolean,
          default: false
        }
    },
    data(){
        return{
            allData: [],
            allRest: [],
            allInfo: [],
            tableCol: [
                { label: '时间节点', prop: '', width: '200' },
                { label: '重量', prop: 'weight', width: '100' },
                { label: '数量', prop: 'num', width: '80' },
                { label: '收运称重人', prop: 'uname', width: '110' },
                { label: '条形码', prop: 'sn', width: '160' },
                { label: '状态', prop: 'status', width: '' },
            ],
            currHospitalId: cookie.get('categoryid'),
            // 筛选可选项
            filter_ld: [],
            filter_lc: [],
            filter_ks: [],
            // 筛选条件
            last_ld: [],
            last_lc: [],
            last_ks: [],
        }
    },
    created(){
        let hw_show_signtime = Cookies.get("hw_show_signtime")
        if(hw_show_signtime && hw_show_signtime == '1'){
            this.tableCol.push({
                label: '科室交接',
                prop: '',
                width: '',
                sub: [
                    { label: '交接确认', prop: 'step1_uname', width: '85' },
                    { label: '交接方式', prop: 'step1_method', width: '85' },
                ]
            })
        }else {
            this.tableCol.push({
                label: '科室交接',
                prop: '',
                width: '',
                sub: [
                    { label: '交接确认', prop: 'step1_uname', width: '85' },
                    { label: '交接方式', prop: 'step1_method', width: '85' },
                    { label: '交接时间', prop: 'step1_time', width: '170' },
                ]
            })
        }
        this.allData = JSON.parse(JSON.stringify(this.data))
        this.allRest = JSON.parse(JSON.stringify(this.restData))
        this.allInfo = JSON.parse(JSON.stringify(this.info))
    },
    watch:{
        'data'(){   // 如果data有变化，则改变内部allData，并重置滚动条
            const all = JSON.parse(JSON.stringify(this.data))
            this.allData = all.map(v => Object.freeze(v))
            this.$nextTick(() => {
              this.$refs.table.bodyWrapper.scrollTop = 0
            })
            this.getFilterList();
        },
        'restData'(){
            const rest = JSON.parse(JSON.stringify(this.restData))
            this.allRest = rest.map(v => Object.freeze(v))
        },
        'info'(){
            const info = JSON.parse(JSON.stringify(this.info))
            this.allInfo = info.map(v => Object.freeze(v))
        }
    },
    computed:{
        computedWays: function(item){
            return function(item){
                return item.filter(v => v.way < 3)
            }
        }
    },
    mounted() {
        this.$refs.table.bodyWrapper.addEventListener('scroll', this.handleScroll, false);  // 监听（绑定）滚轮滚动事件
    },
    methods:{
        handleRowClick(row, column, event){
          this.$emit('row-click', row, column, event)
        },
        judgeTag(tableCol){
            if(this.tag != ''){
                return tableCol.filter(v => {
                    return v.label != '条形码'
                })
            }else{
                return tableCol
            }
        },
        sortByFloor(obj1, obj2){
            let str1 = obj1.lc.substr(0, obj1.lc.indexOf('楼'))
            let str2 = obj2.lc.substr(0, obj2.lc.indexOf('楼'))
            if(str1.indexOf('负') != -1){
                str1 = str1.replace('负','-')
            }
            if(str2.indexOf('负') != -1){
                str2 = str2.replace('负','-')
            }

            return parseInt(str1) - parseInt(str2);
        },
        getFilterList(){
            this.filter_ld = []
            this.filter_lc = []
            this.filter_ks = []

            let ld = new Set(this.allData.map(v => v.ld))
            let lc = new Set(this.allData.map(v => v.lc))
            let ks = new Set(this.allData.map(v => v.ks))

            Array.from(ld).forEach(v => {
                this.filter_ld.push({
                    text: v,
                    value: v
                })
            })
            Array.from(lc).forEach(v => {
                this.filter_lc.push({
                    text: v,
                    value: v
                })
            })
            Array.from(ks).forEach(v => {
                this.filter_ks.push({
                    text: v,
                    value: v
                })
            })

            this.filter_lc.sort((obj1, obj2) => {
                let str1 = obj1.value.substr(0, obj1.value.indexOf('楼'))
                let str2 = obj2.value.substr(0, obj2.value.indexOf('楼'))
                if(str1.indexOf('负') != -1) str1 = str1.replace('负', '-')
                if(str2.indexOf('负') != -1) str2 = str2.replace('负', '-')
                if(str1.indexOf('负') != -1) str1 = str1.replace('负', '-')
                if(str2.indexOf('负') != -1) str2 = str2.replace('负', '-')
            })
        },
        filterItems(data, curr, other1, other2){  // data: 最后要显示的数据 currFilter: 当前筛选的列 other: 其他列
          let curr_arr = this[`last_${curr}`]
          let other1_arr = this[`last_${other1}`]
          let other2_arr = this[`last_${other2}`]
          // 判断当前另外2个是否有值
          if(other1_arr.length != 0){
              data = data.filter(v => other1_arr.indexOf(v[other1]) != -1)
          }
          if(other2_arr.length != 0){
              data = data.filter(v => other2_arr.indexOf(v[other2]) != -1)
          }
          if(curr_arr.length != 0 && other1_arr.length == 0 && other2_arr.length == 0){
              data = data.filter(v => curr_arr.indexOf(v[curr]) != -1)
          }
          // 选择重置，则判断另外2个是否有值
          if(curr_arr.length == 0 && other1_arr.length == 0 && other2_arr.length == 0) {
              data = JSON.parse(JSON.stringify(this.allInfo))
          }
          // 假如都有值，则做过滤
          if(curr_arr.length != 0 && (other1_arr.length != 0 || other2_arr.length != 0)){
              if(other1_arr.length != 0){
                  data = data.filter(v => other1_arr.indexOf(v[other1]) != -1)
              }
              if(other2_arr.length != 0){
                  data = data.filter(v => other2_arr.indexOf(v[other2]) != -1)
              }
              data = data.filter(v => curr_arr.indexOf(v[curr]) != -1)
          }
          return data;
        },
        filterChange(obj){
            this.allData = [];
            this.allRest = [];

            let data = JSON.parse(JSON.stringify(this.allInfo))
            if(obj == undefined){
                this.$refs.table.clearFilter();
            }

            for(let i in obj){
                switch(i){
                    case 'ld': 
                      this.last_ld = obj[i]; 
                      data = this.filterItems(data, 'ld', 'lc', 'ks'); 
                      break;
                    case 'lc': 
                      this.last_lc = obj[i];
                      data = this.filterItems(data, 'lc', 'ld', 'ks');
                      break;
                    case 'ks': 
                      this.last_ks = obj[i];
                      data = this.filterItems(data, 'ks', 'ld', 'lc');
                      break;
                }
            }
            const maxLimit = 50;
            if(data.length > 50){
                this.allData = data.filter((v,i) => i < 50)
                this.allRest = data.filter((v,i) => i >= 50)
            }else{
                this.allData = data;
            }
        },
        filterMethod(value, row, column){
            const property = column['property'];
            return row[property] === value;
        },
        handleShowSign(scope, image){
            this.$emit('showSign', scope.$index, scope.row, image)
        },
        handleShowModal(scope){
            this.$emit('showModal', scope.row)
        },
        handleScroll() {
            let sHeight = this.$refs.table.bodyWrapper.scrollHeight,
                sTop = this.$refs.table.bodyWrapper.scrollTop,
                oHeight = this.$refs.table.bodyWrapper.offsetHeight;    // 滚动条高度
            if(sHeight - sTop < oHeight && this.allRest.length > 0){
                let max = this.allRest.length > 50 ? 50 : this.allRest.length;
                for(let i = 0; i < max; i++){
                    this.allData.push(this.allRest[i])
                }
                this.allRest = this.allRest.filter((v,i) => i > max)
                this.getFilterList();
                this.$emit('updateOrder', this.allData)
            }
        }
    }
}
</script>

<style lang="less">
.pic-item{
    display: block;
    width: 80%;
    margin: auto;
}
.el-table .cell{
    overflow: initial;
}

.el-table {
    .el-popover__reference{
        display: inline-block;
        vertical-align: middle;
        img{
            width: 15px;
            display: block;
        }
    }
    .popover{
        span{
            vertical-align: middle;
        }
    }
}
</style>
